package com.scenic.rd_android.threerd.chart.customchart;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;

/**
 * Created by scenic on 16/9/12.
 */
public class TimerControl {
    private boolean onDetachedFromWindow;
    private long bounceSecond;


    private HandlerThread handlerThread = null;
    private TimerHandler handler;
    private OnTimerRecycleListener onTimerRecycleListener;

    public TimerControl() {
        handlerThread = new HandlerThread("timer-char-data", Process.THREAD_PRIORITY_LOWEST);
        handlerThread.start();
        handler = new TimerHandler(handlerThread.getLooper());
    }


    public void setOnTimerRecycleListener(OnTimerRecycleListener onTimerRecycleListener) {
        this.onTimerRecycleListener = onTimerRecycleListener;

    }

    public TimerControl bounce(long second) {
        bounceSecond = second;
        return this;
    }

    public void stopTimer() {
        onDetachedFromWindow = true;
        handler.removeMessages(TimerHandler.MSG_TIMER);
    }

    public void startTimer() {

        if (bounceSecond > 0) {
//            Observable.timer(bounceSecond, TimeUnit.SECONDS)
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(new Action1<Long>() {
//                        @Override
//                        public void call(Long aLong) {
//
//                            if (stopTimer) {
//                                return;
//                            }
//
//                            request();
//                            startTimer();
//                        }
//                    });
////            }



            handler.sendEmptyMessageDelayed(TimerHandler.MSG_TIMER,0);
        }


    }


    private class TimerHandler extends Handler {

        public static final int MSG_TIMER = 0;

        public TimerHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            if(onDetachedFromWindow){
                return;
            }

            sendEmptyMessageDelayed(MSG_TIMER,bounceSecond * 1000);

            if(onTimerRecycleListener != null){
                onTimerRecycleListener.onTimeRecycle();
            }
        }
    }

    public interface OnTimerRecycleListener {
        /**
         * 运行在子线程的
         */
        void onTimeRecycle();
    }
}
